package com.yellowcong.http.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.yellowcong.kanman.Constants;

/**
 * 网络图片下载工具
 * @author yellowcong
 * @createDate 2015年10月25日
 *
 */
public class HttpImageUtils {

    
    private static HttpImageUtils utils = null;
    private HttpImageUtils() {}
    
    /**
     * 双判断实例化图片下载对象
     */
    public static HttpImageUtils getInstance() {
    	if(utils == null) {
    		synchronized (HttpImageUtils.class) {
				if(utils == null) {
					utils = new HttpImageUtils();
				}
			}
    	}
    	return utils;
    }
    
    /**
     * 下载图片
     */
    public boolean downloadImage(String urlPathStr,String imageName){
        FileOutputStream out   = null;
        InputStream in = null;
        boolean flag = false;
        try {
            //获取URL
            URL url = new URL(urlPathStr);

            //获取连接
            URLConnection conn  = url.openConnection();
            //设定连接的属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("conn", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //百度
            //Baiduspider+(+http://www.baidu.com/search/spider.htm)
            //火狐
            //Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)
            //设定 ip 设定成百度的
            conn.setRequestProperty("X-Forwarded-For", "117.28.255.37");
            conn.setRequestProperty("Client-Ip", "117.28.255.37");

            in = conn.getInputStream();
            
            //当文件夹不存在就创建
            File file = new File(imageName);
            mkdirIfNotExit(file.getParentFile());
            
            //写出图片
            out = new FileOutputStream(file);
            byte [] buff = new byte[1024];
            int len = 0;
            while((len = in.read(buff))!= -1){
                //写数据
                out.write(buff, 0, len);
            }
            System.err.println("------------------"+imageName+"下载成功------------------------");
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    
    /**
      * 创建日期:2018/02/28<br/>
      * 创建时间:9:34:15<br/>
      * 创建用户:yellowcong<br/>
      * 机能概要:创建文件夹，如果不存在的情况
      * @param path
     */
    public void mkdirIfNotExit(File outPath ) {
    	if(!outPath.exists()) {
    		outPath.mkdirs();
    	}
    }
    
}